<template>
	<view class="content">
		<view @click="tonew"> 跳转新页面</view>
		<view class="user-info">
			<view class="title">
				<image class="rose-icon" src="/static/img/mili1.png" mode=""></image>
				<text>我的米币</text>
			</view>
			<view class="balance">{{info.rose}}</view>
		</view>
		<view class="rose-wrap">
			<view class="rose-list">
				<view class="rose-item" v-for="(item, index) in list" :key="item.id">
					<image class="rose-icon" src="/static/img/mili1.png" mode=""></image>
					<view class="label">{{item.name}}</view>
					<view class="value">
						<view v-if="item.give_rose > 0 || item.give_vip_day > 0" class="tips">
							<text>特惠折扣</text>
						</view>
						<view class="text">
							<text v-if="item.give_rose > 0">送{{item.give_rose}}米币</text>
							<text v-if="item.give_vip_day > 0">送VIP{{item.give_vip_day}}天</text>
						</view>
					</view>
					<button class="pay-btn" type="primary" size="mini" @click="requestOrder(item)">￥{{item.money}}</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { JSEncrypt } from 'jsencrypt/bin/jsencrypt';
	export default {
		data() {
			return {
				myInfo: {},
				platform: '',
				info: {
					rose: 0,
				},
				list: [],
				iapChannel: null,
				product_list: '',
			}
		},
		onLoad(options) {
			try {
				const myInfo = uni.getStorageSync('myInfo');
				if (myInfo) {
					this.myInfo = myInfo;
				}
			} catch (e) {
				console.log(e)
			}
			try {
				const systemInfo = uni.getSystemInfoSync();
				if (systemInfo) {
					this.platform = systemInfo.platform;
				}
			} catch (e) {
				console.log(e)
			}
			// 更新米币数量
			uni.$on('my-page', data => {
				if (data.type == 'update') {
					console.log('更新米币数量')
					this.getRose();
				}
			})
			this.getRose();
			this.getIPA();  //获取支付渠道
			
			
		},
		onReady() {
		},
		onNavigationBarButtonTap(e) {
			uni.navigateTo({
				url: 'my_paylog'
			})
		},
		onPullDownRefresh() {
			setTimeout(() => {
				this.getRose();
			}, 500)
		},
		methods: {
			tonew:function(){
				uni.navigateTo({
					url:'./rose_copy'
				})
			},
			getIPA: function () {
			    plus.payment.getChannels(channels => {
			        // 获取苹果内购渠道
			        for (let i = 0; i < channels.length; i++) {
						if (channels[i].id == 'appleiap') {
						    this.iapChannel = channels[i];
							this.restoreComplateRequest();
							
						}  
			        }
			    }, e => {  
			        console.log("获取支付通道失败：", e);  
			    });
			},
			
			// 创建内购项目订单
			requestOrder:function(item) {
			    var _this=this;
				if(item.apple_id=="" ){
					uni.showToast({
						title: '后台未配置支付id，暂不能支付',
						position: 'bottom',
						icon: 'none'
					});
					return
				}
				uni.showLoading({
					title: '正在创建订单请稍后....'
				});
			    _this.iapChannel.requestOrder(
			        [item.apple_id],
			        res => {
						uni.hideLoading()
						_this.product_list = res;
					    _this.payFun(res);
						
			        },
			        function(errormsg) {
			            plus.nativeUI.alert("获取应用内购项目失败，请稍后重试。", function() {}, "提示");
			        }
			    )
			},
			
			// 调起支付
			payFun: function(i) {
				uni.showLoading({
					title: '拉起支付'
				});
				setTimeout(function(){
					uni.hideLoading()
				},2000)
				
			    let _this=this;
			    plus.payment.request(_this.iapChannel, {
					 productid: i[0].productid,
					 optimize: true ,      // 支付时设置 optimize: true  
					}, 
					function(result){
						
						uni.showToast({
							title: '支付成功',
							position: 'bottom',
							icon: 'none'
						});
						
						var cc=JSON.stringify(result);
						uni.request({
							url: 'http://atm.sanfuhai.cn/api/ios',
							method: 'POST',
							header: {'content-type': 'application/x-www-form-urlencoded'},
							data: {form:cc,type:'rose',uid: _this.myInfo.id,},
							success: res => {
								uni.hideLoading();
								if (res.statusCode == 200) {
									if(res.data=='success'){
										//更新米币数量
										uni.$emit('my-page', {
											type: 'update',
										})
									}
								}
							},
							fail: err => {
								console.log('失败返回信息',err)
							}
						})	
					
						
					}, function(e){
						// 用户取消支付或者调起支付失败回调
						_this.restoreComplateRequest()
			        });	
			},
			
			// 获取已购的非消耗性商品和订阅商品
			restoreComplateRequest: function() {
				this.iapChannel.restoreComplateRequest({}, results => {
					// results 格式为数组存放恢复的IAP商品交易信息对象 IAPTransaction，通用需将返回的支付凭证传给后端进行二次认证  
					uni.showToast({
						title: '11111支付成功回调'+JSON.stringify(results),
						position: 'bottom',
						icon: 'none'
					});
					
				}, e => {
					uni.showToast({
						title: '失败回调'+JSON.stringify(e),
						position: 'bottom',
						icon: 'none'
					});
					
				});
			},   
			
			getRose: function () {
				uni.showLoading({
					title: ''
				});
				this.$api.api.ajaxData({
					method: 'V1.Rose',
					uid: this.myInfo.id,
					token: this.myInfo.token
				}, res => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
					if (res.status) {
						this.info = res.data.info
						this.list = res.data.list
					} else {
						uni.showToast({
							title: res.msg,
							position: 'bottom',
							icon: 'none'
						});
					}
				}, err => {
					uni.hideLoading();
					uni.showToast({
						title: '网络错误，请稍后再试',
						position: 'bottom',
						icon: 'none'
					});
				})
			},
			// 加密
			enphone(msg){
				let pubkey = '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAbfx4VggVVpcfCjzQ+nEiJ2DLnRg3e2QdDf/m/qMvtqXi4xhwvbpHfaX46CzQznU8l9NJtF28pTSZSKnE/791MJfVnucVcJcxRAEcpPprb8X3hfdxKEEYjOPAuVseewmO5cM+x7zi9FWbZ89uOp5sxjMnlVjDaIczKTRx+7vn2wIDAQAB-----END PUBLIC KEY-----'; // 公钥
				var encrypt = new JSEncrypt();
				encrypt.setPublicKey(pubkey);
				return encrypt.encrypt(msg);
			},
		}
	}
</script>

<style lang="scss">
	@import '../../common/common.scss';
	.user-info {
		background-color: #fff;
		padding: 50rpx;
		.title {
			display: flex;
			justify-content: center;
			align-items: center;
			.rose-icon {
				width: 50rpx;
				height: 50rpx;
				margin-right: 10rpx;
			}
			text {
				font-size: 30rpx;
				color: #333;
			}
		}
		.balance {
			text-align: center;
			font-size: 48rpx;
			font-weight: 700;
			color: #FF71A5;
		}
	}
	.rose-wrap {
		margin: 20rpx;
		.rose-list {
			background-color: #fff;
			border-radius: 20rpx;
		}
		.rose-item {
			display: flex;
			justify-content: flex-start;
			align-items: center;
			padding: 20rpx;
			& + .rose-item {
				border-top: 1rpx solid #efefef;
			}
			.rose-icon {
				width: 50rpx;
				height: 50rpx;
				margin-right: 10rpx;
			}
			.label {
				font-size: 30rpx;
				color: #333;
			}
			.value {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: flex-start;
				flex: 1;
				padding: 0 10rpx;
				.tips {
					display: flex;
					justify-content: center;
					align-items: center;
					height: 30rpx;
					padding: 0 20rpx;
					background-color: #ED4574;
					border-radius: 5rpx;
					text {
						font-size: 16rpx;
						color: #fff;
					}
				}
				.text {
					display: flex;
					justify-content: flex-start;
					align-items: center;
					height: 40rpx;
					padding: 0 5rpx;
					text {
						font-size: 20rpx;
						color: #FF71A5;
						margin-right: 10rpx;
					}
				}
			}
			.pay-btn {
				border-radius: 100rpx;
			}
		}
	}
</style>
